<template>
  <div class="defect-associations">
    <el-tabs v-model="activeSubTab" type="border-card" class="association-sub-tabs">
      <!-- 关联需求子页签 -->
      <el-tab-pane label="关联需求" name="requirements">
        <div class="sub-tab-content">
          <div class="tab-header">
            <div class="header-info">
              <span class="item-count">关联需求（{{ relatedRequirement ? 1 : 0 }}）</span>
            </div>
            <div class="header-actions">
              <el-button
                v-if="!relatedRequirement"
                type="primary"
                size="small"
                @click="handleAddRequirement"
              >
                <el-icon><Plus /></el-icon>
                添加需求
              </el-button>
              <el-button
                v-else
                type="danger"
                size="small"
                @click="handleRemoveRequirement"
              >
                <el-icon><Delete /></el-icon>
                移除关联
              </el-button>
            </div>
          </div>

          <div v-loading="requirementsLoading" class="items-list">
            <el-table
              v-if="relatedRequirement"
              :data="[relatedRequirement]"
              size="default"
              border
              stripe
              style="width: 100%"
            >
              <el-table-column prop="title" label="需求标题" min-width="200" show-overflow-tooltip>
                <template #default="{ row }">
                  <el-link
                    type="primary"
                    @click="handleViewRequirement(row.id)"
                    :underline="false"
                  >
                    {{ row.title }}
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag
                    :type="getRequirementStatusType(row.status)"
                    size="small"
                  >
                    {{ getRequirementStatusName(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="priority" label="优先级" width="90">
                <template #default="{ row }">
                  <el-tag
                    :type="getRequirementPriorityType(row.priority)"
                    size="small"
                  >
                    {{ getRequirementPriorityName(row.priority) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="assignee_name" label="负责人" width="100" show-overflow-tooltip />
              <el-table-column prop="created_at" label="创建时间" width="160">
                <template #default="{ row }">
                  {{ formatDate(row.created_at) || '—' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="{ row }">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="handleViewRequirement(row.id)"
                  >
                    查看
                  </el-button>
                  <el-button
                    link
                    type="danger"
                    size="small"
                    @click="handleRemoveRequirement"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无关联需求" :image-size="80" />
          </div>
        </div>
      </el-tab-pane>

      <!-- 关联任务子页签 -->
      <el-tab-pane label="关联任务" name="tasks">
        <div class="sub-tab-content">
          <div class="tab-header">
            <div class="header-info">
              <span class="item-count">关联任务（{{ relatedTasks.length }}）</span>
            </div>
            <div class="header-actions">
              <el-button
                type="primary"
                size="small"
                @click="handleAddTask"
              >
                <el-icon><Plus /></el-icon>
                添加任务
              </el-button>
            </div>
          </div>

          <div v-loading="tasksLoading" class="items-list">
            <el-table
              v-if="relatedTasks.length > 0"
              :data="relatedTasks"
              size="default"
              border
              stripe
              style="width: 100%"
            >
              <el-table-column prop="title" label="任务标题" min-width="200" show-overflow-tooltip>
                <template #default="{ row }">
                  <el-link
                    type="primary"
                    @click="handleViewTask(row.id)"
                    :underline="false"
                  >
                    {{ row.title }}
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag
                    :type="getTaskStatusType(row.status)"
                    size="small"
                  >
                    {{ getTaskStatusName(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="priority" label="优先级" width="90">
                <template #default="{ row }">
                  <el-tag
                    :type="getTaskPriorityType(row.priority)"
                    size="small"
                  >
                    {{ getTaskPriorityName(row.priority) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="assignee_name" label="负责人" width="100" show-overflow-tooltip />
              <el-table-column prop="due_date" label="截止日期" width="110">
                <template #default="{ row }">
                  {{ formatDate(row.due_date) || '—' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="{ row }">
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="handleViewTask(row.id)"
                  >
                    查看
                  </el-button>
                  <el-button
                    link
                    type="danger"
                    size="small"
                    @click="handleRemoveTask(row)"
                  >
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无关联任务" :image-size="80" />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加需求对话框 -->
    <el-dialog
      v-model="requirementDialogVisible"
      title="选择需求"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <el-input
          v-model="requirementSearch"
          placeholder="搜索需求标题"
          clearable
          @input="handleRequirementSearch"
          style="margin-bottom: 16px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-table
          v-loading="requirementListLoading"
          :data="requirementList"
          border
          stripe
          max-height="400"
          @row-click="handleSelectRequirement"
        >
          <el-table-column prop="title" label="需求标题" min-width="200" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag
                :type="getRequirementStatusType(row.status)"
                size="small"
              >
                {{ getRequirementStatusName(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="优先级" width="90">
            <template #default="{ row }">
              <el-tag
                :type="getRequirementPriorityType(row.priority)"
                size="small"
              >
                {{ getRequirementPriorityName(row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="assignee_name" label="负责人" width="100" show-overflow-tooltip />
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button
                link
                type="primary"
                size="small"
                @click.stop="handleSelectRequirement(row)"
              >
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="requirementTotal > 0"
          v-model:current-page="requirementPage"
          v-model:page-size="requirementPageSize"
          :total="requirementTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadRequirements"
          @current-change="loadRequirements"
          style="margin-top: 16px; justify-content: flex-end"
        />
      </div>
    </el-dialog>

    <!-- 添加任务对话框 -->
    <el-dialog
      v-model="taskDialogVisible"
      title="选择任务"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <el-input
          v-model="taskSearch"
          placeholder="搜索任务标题"
          clearable
          @input="handleTaskSearch"
          style="margin-bottom: 16px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-table
          v-loading="taskListLoading"
          :data="taskList"
          border
          stripe
          max-height="400"
          @row-click="handleSelectTask"
        >
          <el-table-column prop="title" label="任务标题" min-width="200" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag
                :type="getTaskStatusType(row.status)"
                size="small"
              >
                {{ getTaskStatusName(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="优先级" width="90">
            <template #default="{ row }">
              <el-tag
                :type="getTaskPriorityType(row.priority)"
                size="small"
              >
                {{ getTaskPriorityName(row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="assignee_name" label="负责人" width="100" show-overflow-tooltip />
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button
                link
                type="primary"
                size="small"
                @click.stop="handleSelectTask(row)"
              >
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="taskTotal > 0"
          v-model:current-page="taskPage"
          v-model:page-size="taskPageSize"
          :total="taskTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadTasks"
          @current-change="loadTasks"
          style="margin-top: 16px; justify-content: flex-end"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Search } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { taskAPI, getTaskList, type Task } from '@/api/task'
import { getRequirements, getRequirementById, type RequirementResponse } from '@/api/requirements'
import { updateDefect } from '@/api/defect'
import { formatDate } from '@/utils/date'
import { useTaskStates } from '@/composables/useTaskStates'
import { useRequirementStates } from '@/composables/useRequirementStates'
import { useRequirementOptions } from '@/composables/useRequirementOptions'
import { priorityApi } from '@/api/priority'
import { TASK_PRIORITIES } from '@/types/task'
import type { Defect } from '@/api/defect'

interface Props {
  defectId: string
  defect?: Defect | null
  projectId?: string
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'updated'): void
}>()

const router = useRouter()
const activeSubTab = ref('requirements')
const requirementsLoading = ref(false)
const tasksLoading = ref(false)
const relatedRequirement = ref<RequirementResponse | null>(null)
const relatedTasks = ref<Task[]>([])

const { loadStates: loadTaskStates, getStateName: getTaskStateName } = useTaskStates()
const { getStateName: getRequirementStateName, getStateColor: getRequirementStateColor, loadStates: loadRequirementStates } = useRequirementStates()
const { getPriorityName: getRequirementPriorityNameFromOptions, getPriorityType: getRequirementPriorityTypeFromOptions, loadOptions: loadRequirementOptions } = useRequirementOptions()

// 任务优先级选项
const taskPriorityOptions = ref<Array<{ value: string; label: string }>>([])

// 加载任务优先级选项
const loadTaskPriorityOptions = async () => {
  try {
    const response = await priorityApi.getAll('task')
    if (response && response.data && response.data.success && response.data.data) {
      taskPriorityOptions.value = response.data.data.map((p: any) => ({
        value: p.code,
        label: p.name
      }))
    } else {
      taskPriorityOptions.value = TASK_PRIORITIES.map(p => ({
        value: p.value,
        label: p.label
      }))
    }
  } catch (error) {
    console.error('加载任务优先级失败:', error)
    taskPriorityOptions.value = TASK_PRIORITIES.map(p => ({
      value: p.value,
      label: p.label
    }))
  }
}

const getTaskStatusName = (status?: string) => {
  if (!status) return '未知'
  return getTaskStateName(status)
}

const getTaskStatusType = (status?: string) => {
  if (!status) return 'info'
  const code = status.toLowerCase()
  if (code === 'done' || code === 'completed') return 'success'
  if (code === 'in_progress' || code === 'inprogress') return 'warning'
  return 'info'
}

const getTaskPriorityName = (priority?: string) => {
  if (!priority) return '未知'
  const option = taskPriorityOptions.value.find(p => p.value === priority)
  return option ? option.label : priority
}

const getTaskPriorityType = (priority?: string) => {
  if (!priority) return 'info'
  const code = priority.toLowerCase()
  if (code === 'urgent' || code === 'critical' || code === 'blocker') return 'danger'
  if (code === 'high') return 'warning'
  if (code === 'medium') return 'success'
  return 'info'
}

const getRequirementStatusName = (status?: string) => {
  if (!status) return '未知'
  return getRequirementStateName(status)
}

const getRequirementStatusType = (status?: string) => {
  if (!status) return 'info'
  const color = getRequirementStateColor(status)
  if (color.includes('green') || color.includes('success')) return 'success'
  if (color.includes('red') || color.includes('danger')) return 'danger'
  if (color.includes('orange') || color.includes('warning')) return 'warning'
  return 'info'
}

const getRequirementPriorityName = (priority?: string) => {
  if (!priority) return '未知'
  return getRequirementPriorityNameFromOptions(priority)
}

const getRequirementPriorityType = (priority?: string) => {
  if (!priority) return 'info'
  return getRequirementPriorityTypeFromOptions(priority)
}

// 加载关联需求
const loadRelatedRequirement = async () => {
  if (!props.defect?.requirement_id) {
    relatedRequirement.value = null
    return
  }

  try {
    requirementsLoading.value = true
    const response = await getRequirementById(props.defect.requirement_id)
    if (response && response.success && response.data) {
      relatedRequirement.value = response.data
    } else {
      relatedRequirement.value = null
    }
  } catch (error) {
    console.error('加载关联需求失败:', error)
    relatedRequirement.value = null
  } finally {
    requirementsLoading.value = false
  }
}

// 加载关联任务（通过需求关联）
const loadRelatedTasks = async () => {
  if (!props.defect?.requirement_id) {
    relatedTasks.value = []
    return
  }

  try {
    tasksLoading.value = true
    await loadTaskStates()
    
    const response = await getTaskList({
      project_id: props.projectId || props.defect?.project_id,
      requirement_id: props.defect.requirement_id,
      page: 1,
      size: 100
    })
    
    relatedTasks.value = response.items || []
  } catch (error) {
    console.error('加载关联任务失败:', error)
    ElMessage.error('加载关联任务失败')
    relatedTasks.value = []
  } finally {
    tasksLoading.value = false
  }
}

// 添加需求对话框
const requirementDialogVisible = ref(false)
const requirementListLoading = ref(false)
const requirementList = ref<RequirementResponse[]>([])
const requirementSearch = ref('')
const requirementPage = ref(1)
const requirementPageSize = ref(20)
const requirementTotal = ref(0)

const loadRequirements = async () => {
  if (!props.projectId && !props.defect?.project_id) {
    ElMessage.warning('请先选择项目')
    return
  }

  try {
    requirementListLoading.value = true
    const response = await getRequirements({
      project_id: props.projectId || props.defect?.project_id,
      search: requirementSearch.value || undefined,
      page: requirementPage.value,
      size: requirementPageSize.value
    })
    
    if (response && response.success && response.data) {
      const data = response.data
      if (Array.isArray(data)) {
        requirementList.value = data
        // 从pagination获取总数
        if (response.pagination) {
          requirementTotal.value = response.pagination.total || data.length
        } else {
          requirementTotal.value = data.length
        }
      } else {
        requirementList.value = []
        requirementTotal.value = 0
      }
    } else {
      requirementList.value = []
      requirementTotal.value = 0
    }
  } catch (error) {
    console.error('加载需求列表失败:', error)
    ElMessage.error('加载需求列表失败')
    requirementList.value = []
    requirementTotal.value = 0
  } finally {
    requirementListLoading.value = false
  }
}

const handleRequirementSearch = () => {
  requirementPage.value = 1
  loadRequirements()
}

const handleAddRequirement = () => {
  requirementDialogVisible.value = true
  requirementPage.value = 1
  requirementSearch.value = ''
  loadRequirements()
}

const handleSelectRequirement = async (requirement: RequirementResponse) => {
  try {
    await updateDefect(props.defectId, {
      requirement_id: requirement.id
    })
    ElMessage.success('关联需求成功')
    requirementDialogVisible.value = false
    await loadRelatedRequirement()
    await loadRelatedTasks()
    emit('updated')
  } catch (error: any) {
    console.error('关联需求失败:', error)
    ElMessage.error(error.message || '关联需求失败')
  }
}

const handleRemoveRequirement = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要移除需求"${relatedRequirement.value?.title}"的关联吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await updateDefect(props.defectId, {
      requirement_id: undefined
    })
    ElMessage.success('移除需求关联成功')
    await loadRelatedRequirement()
    await loadRelatedTasks()
    emit('updated')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('移除需求关联失败:', error)
      ElMessage.error(error.message || '移除需求关联失败')
    }
  }
}

// 添加任务对话框
const taskDialogVisible = ref(false)
const taskListLoading = ref(false)
const taskList = ref<Task[]>([])
const taskSearch = ref('')
const taskPage = ref(1)
const taskPageSize = ref(20)
const taskTotal = ref(0)

const loadTasks = async () => {
  if (!props.projectId && !props.defect?.project_id) {
    ElMessage.warning('请先选择项目')
    return
  }

  try {
    taskListLoading.value = true
    const response = await getTaskList({
      project_id: props.projectId || props.defect?.project_id,
      search: taskSearch.value || undefined,
      page: taskPage.value,
      size: taskPageSize.value
    })
    
    taskList.value = response.items || []
    taskTotal.value = response.total || 0
  } catch (error) {
    console.error('加载任务列表失败:', error)
    ElMessage.error('加载任务列表失败')
  } finally {
    taskListLoading.value = false
  }
}

const handleTaskSearch = () => {
  taskPage.value = 1
  loadTasks()
}

const handleAddTask = async () => {
  if (!props.defect?.requirement_id) {
    ElMessage.warning('请先关联需求，任务将通过需求间接关联')
    return
  }
  
  taskDialogVisible.value = true
  taskPage.value = 1
  taskSearch.value = ''
  loadTasks()
}

const handleSelectTask = async (task: Task) => {
  try {
    // 将任务关联到缺陷关联的需求
    await taskAPI.updateTask(task.id, {
      requirement_id: props.defect?.requirement_id
    })
    ElMessage.success('关联任务成功')
    taskDialogVisible.value = false
    await loadRelatedTasks()
    emit('updated')
  } catch (error: any) {
    console.error('关联任务失败:', error)
    ElMessage.error(error.message || '关联任务失败')
  }
}

const handleRemoveTask = async (task: Task) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除任务"${task.title}"的关联吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 移除任务的requirement_id关联
    await taskAPI.updateTask(task.id, {
      requirement_id: null
    })
    ElMessage.success('移除任务关联成功')
    await loadRelatedTasks()
    emit('updated')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('移除任务关联失败:', error)
      ElMessage.error(error.message || '移除任务关联失败')
    }
  }
}

// 查看需求
const handleViewRequirement = (requirementId: string) => {
  router.push(`/requirements/${requirementId}`)
}

// 查看任务
const handleViewTask = (taskId: string) => {
  router.push(`/tasks/${taskId}`)
}

watch(() => [props.defectId, props.defect?.requirement_id], () => {
  loadRelatedRequirement()
  loadRelatedTasks()
}, { immediate: true, deep: true })

onMounted(async () => {
  await Promise.all([
    loadTaskStates(),
    loadRequirementStates(),
    loadRequirementOptions(),
    loadTaskPriorityOptions()
  ])
  loadRelatedRequirement()
  loadRelatedTasks()
})
</script>

<style scoped lang="scss">
.defect-associations {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

.association-sub-tabs {
  :deep(.el-tabs__content) {
    padding: 0;
  }
}

.sub-tab-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.item-count {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.items-list {
  min-height: 200px;
}

.dialog-content {
  padding: 8px 0;
}
</style>

